package database

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"shortUrl/internal/config"
	"time"
)

func New(c *config.DataBaseConf) *gorm.DB {
	dataSource := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8mb4&parseTime=True&loc=Local&multiStatements=true",
		c.Username,
		c.Password,
		c.Host,
		c.Database,
	)
	db, err := gorm.Open(mysql.Open(dataSource), &gorm.Config{
		Logger: logger.Default.LogMode(c.LogLevel),
	})

	if err != nil {
		panic("数据库连接失败,error=" + err.Error())
	} else {
		fmt.Println("数据库连接成功")
	}
	sqlDb, _ := db.DB()
	sqlDb.SetMaxIdleConns(5)
	sqlDb.SetMaxOpenConns(100)
	sqlDb.SetConnMaxLifetime(time.Hour)       // 连接的最大生命周期
	sqlDb.SetConnMaxIdleTime(5 * time.Minute) // 连接的最大空闲时间
	return db
}
